<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
            <!-- 路径导航 -->
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>分类参数</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!-- 提示文本 -->
        <el-alert title="注意：只允许未第三季分类设置相关参数" type="warning" show-icon></el-alert>
        <!-- 选择商品分类 -->
        <div>
            <span>请选择商品分类</span> &nbsp;&nbsp;
            <el-cascader
                :options="cateAllList"
                clearable
                v-model="cateId"
                @change="getParamsList"
                :props="{value:'cat_id',label:'cat_name' }"
            ></el-cascader>
        </div>
        <!-- 标签页 -->
        <el-tabs v-model="activeName" @tab-click="getParamsList">
            <el-tab-pane label="动态参数" name="many">
                <el-button
                    type="primary"
                    size="default"
                    :disabled="idBtnabled"
                    @click="dialogShow=true"
                >添加动态参数</el-button>
                <!-- 动态参数表格 -->
                <el-table :data="manyList" border style="width: 100%">
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag
                                :key="tag"
                                v-for="(tag,idx) in scope.row.attr_vals"
                                closable
                                :disable-transitions="false"
                                @close="handleClose(scope.row,idx)"
                            >{{tag}}</el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                            ></el-input>
                            <el-button
                                v-else
                                class="button-new-tag"
                                size="small"
                                @click="showInput(scope.row)"
                            >+ 增加</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="序号" width="100px"></el-table-column>
                    <el-table-column prop="attr_name" label="参数名"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button
                                type="success"
                                size="small"
                                icon="el-icon-s-tools"
                                @click="edit(scope.row)"
                            ></el-button>
                            <el-button
                                type="danger"
                                size="small"
                                icon="el-icon-delete"
                                @click="del(scope.row)"
                            ></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button
                    type="primary"
                    size="default"
                    :disabled="idBtnabled"
                    @click="dialogShow=true"
                >添加静态参数</el-button>
                <!-- 静态参数表格 -->
                <el-table :data="onlyList" border style="width: 100%">
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag
                                :key="tag"
                                v-for="(tag,idx) in scope.row.attr_vals"
                                closable
                                :disable-transitions="false"
                                @close="handleClose(scope.row,idx)"
                            >{{tag}}</el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                            ></el-input>
                            <el-button
                                v-else
                                class="button-new-tag"
                                size="small"
                                @click="showInput(scope.row)"
                            >+ 增加</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="序号" width="100px"></el-table-column>
                    <el-table-column prop="attr_name" label="参数名"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button
                                type="success"
                                size="small"
                                icon="el-icon-s-tools"
                                @click="edit(scope.row)"
                            ></el-button>
                            <el-button
                                type="danger"
                                size="small"
                                icon="el-icon-delete"
                                @click="del(scope.row)"
                            ></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <!-- 参数弹框 -->
        <el-dialog
            @close="close"
            :title="isAdd? activeName==='many'?'添加动态参数':'添加静态参数':activeName==='many'?'修改动态参数':'修改静态参数'"
            :visible.sync="dialogShow"
            width="40%"
        >
            <!-- 表单区域 -->
            <el-form
                :model="form"
                ref="form"
                :rules="formRules"
                label-width="100px"
                v-if="dialogShow"
            >
                <el-form-item :label="activeName==='many'?'动态参数名':'静态参数名'" prop="attr_name">
                    <el-input v-model="form.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click=" dialogShow= false">取消</el-button>
                <el-button type="primary" @click="submit">确定</el-button>
            </span>
        </el-dialog>
    </el-card>
</template>

<script>
export default {
    data() {
        return {
            cateAllList: [],
            activeName: "many",
            cateId: [],
            idBtnabled: true, //添加按钮是否启用
            onlyList: [], // 静态参数列表
            manyList: [], // 动态参数列表
            isAdd: true, // 是否是添加行为
            dialogShow: false,
            // 表单对象
            form: {
                attr_name: "",
            },
            // 验证规则对象
            formRules: {
                attr_name: [
                    {
                        required: true,
                        message: "请输入内容",
                        trigger: "blur",
                    },
                ],
            },
            attrId: "",
        };
    },

    created() {
        this.getAllCateList();
    },
    methods: {
        close() {
            this.form.attr_name = "";
            this.isAdd = true;
        },
        // 打开输入框
        showInput(row) {
            row.inputVisible = true;
            this.$nextTick((_) => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 删除标签
        async handleClose(row, index) {
            try {
                await this.$confirm("您确定要删除吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                });
                let attr_vals_old = [...row.attr_vals];
                attr_vals_old.splice(index, 1);
                let { data: res } = await this.$axios.put(
                    `categories/${row.cat_id}/attributes/${row.attr_id}`,
                    {
                        attr_name: row.attr_name,
                        attr_sel: row.attr_sel,
                        attr_vals: attr_vals_old.join(","),
                    }
                );
                if (res.meta.status !== 200)
                    return this.$message.error(res.meta.msg);
                this.$message.success("删除成功");
                row.attr_vals.splice(index, 1);
            } catch (error) {
                this.$message.info("取消删除");
            }
        },
        // 失去焦点的处理函数
        async handleInputConfirm(row) {
            console.log(row);
            let attr_vals_all = [...row.attr_vals, row.inputValue];
            if (row.inputValue) {
                let { data: res } = await this.$axios.put(
                    `categories/${row.cat_id}/attributes/${row.attr_id}`,
                    {
                        attr_name: row.attr_name,
                        attr_sel: row.attr_sel,
                        attr_vals: attr_vals_all.join(","),
                    }
                );
                if (res.meta.status !== 200)
                    return this.$message.error(res.meta.msg);
                this.$message.success("添加成功");
                row.attr_vals.push(row.inputValue);
                row.inputValue = "";
            }
            row.inputVisible = false;
        },
        // 获取商品全部分类列表
        async getAllCateList() {
            let { data: res } = await this.$axios.get("categories");
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);

            this.cateAllList = res.data;
        },
        // 获取静态动态数据的方法
        async getParamsList() {
            if (this.cateId.length != 3) {
                this.idBtnabled = true;
                this.onlyList = [];
                this.manyList = [];
                return;
            }
            this.idBtnabled = false;
            let id = this.cateId[2];
            let { data: res } = await this.$axios.get(
                "categories/" + id + "/attributes",
                {
                    params: {
                        sel: this.activeName,
                    },
                }
            );
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            res.data.forEach((item) => {
                item.attr_vals =
                    item.attr_vals.length === 0
                        ? []
                        : item.attr_vals.split(",");
                item.inputVisible = false;
                item.inputValue = "";
            });
            this[this.activeName + "List"] = res.data;
        },
        // 点击删除的事件函数
        async del(row) {
            try {
                await this.$confirm("您确定要删除吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                });
                let { data: res } = await this.$axios.delete(
                    `categories/${row.cat_id}/attributes/${row.attr_id}`
                );
                if (res.meta.status !== 200)
                    return this.$message.error(res.meta.msg);
                this.$message.success("删除成功");
                this.getParamsList();
            } catch (error) {
                this.$message.error("取消删除");
            }
        },
        // 点击修改的事件函数
        edit(row) {
            console.log(row);
            (this.attrId = row.attr_id), (this.form.attr_name = row.attr_name);
            this.isAdd = false;
            this.dialogShow = true;
        },
        // 添加和修改的提交
        submit() {
            // 判断是否验证通过
            this.$refs.form.validate(async (valid) => {
                if (!valid) return;
                // 判断是否是添加
                let id = this.cateId[2];
                let method, url;
                if (this.isAdd) {
                    method = "post";
                    url = `categories/${id}/attributes`;
                } else {
                    method = "put";
                    url = `categories/${id}/attributes/${this.attrId}`;
                }

                let { data: res } = await this.$axios({
                    url,
                    method,
                    data: {
                        attr_name: this.form.attr_name,
                        attr_sel: this.activeName,
                    },
                });
                if (![200, 201].includes(res.meta.status))
                    return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);
                // 关闭弹框
                this.dialogShow = false;
                this.getParamsList();
                this.isAdd = true;
            });
        },
    },
};
</script>

<style lang="less">
.el-alert {
    margin-bottom: 20px !important;
}

.el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px !important;
    margin-left: 10px;
}
</style>